#include "jvmtest.h"

JvmTest::JvmTest(QObject *parent) : QObject(parent)
{

}

void JvmTest::test(){
    JavaVM* jvm;       // 指向Java虚拟机的指针
    JNIEnv* env;       // JNI接口指针
    JavaVMInitArgs vm_args; // JVM初始化参数
    JavaVMOption options[1];

    // 设置JVM选项，例如类路径
    options[0].optionString = const_cast<char*>("-Djava.class.path=D:\\temp\\demo\\build\\libs\\demo-1.0-SNAPSHOT.jar");

    vm_args.version = JNI_VERSION_1_8;
    vm_args.nOptions = 1;
    vm_args.options = options;
    vm_args.ignoreUnrecognized = false;

    // 启动JVM
    jint res = JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args);
    if (res != JNI_OK) {
        qDebug("Failed to create JVM");
    }

    // 查找你要调用的类
    jclass cls = env->FindClass("org/example/Main");
    if (cls == nullptr) {
        qCritical("Failed to find class");
        jvm->DestroyJavaVM();
    }

    // 获取你想要调用的方法ID（这里假设是一个静态方法）
    jmethodID mid = env->GetStaticMethodID(cls, "add", "(II)I"); // 注意方法签名
    if (mid == nullptr) {
        qCritical("Failed to find method");
        jvm->DestroyJavaVM();
    }
    jint result = env->CallStaticIntMethod(cls, mid, 2, 3);
    qInfo() << "2+3=" + QString::number(result);

    // 关闭JVM
    jvm->DestroyJavaVM();
}
